package com.stary.code.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * <p>jdbc工具类</p>
 * @author stary {@link stary1993@qq.com}
 * @since 2018-7-23
 */
public class JdbcUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
	
	/**
	 * 获取数据源连接
	 * @param driverClassName 驱动类名
	 * @param url 链接
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnection(String driverClassName, String url, 
			String username, String password) throws SQLException, ClassNotFoundException {             
		Class.forName(driverClassName);		
		Connection conn = DriverManager.getConnection(url, username, password); 			
		return conn;
	}
	/**
	 * 关闭数据库连接
	 * @param conn
	 */
	public static void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error("close connection failure", e);
			}
		}
	}
	/**
	 * 获取数据库下的所有表名
	 * @param driverClassName 驱动类名
	 * @param url 链接
	 * @param username 用户名
	 * @param password 密码
	 * @throws SQLException 
	 * @throws ClassNotFoundException
	 */
	public static List<String> getTableNames(String driverClassName, String url, 
			String username, String password) throws ClassNotFoundException, SQLException {
		List<String> tableNames = new ArrayList<>();
		Connection conn = getConnection( driverClassName, url, username, password);
		ResultSet rs = null;
		try {
			//获取数据库的元数据
			DatabaseMetaData db = conn.getMetaData();			
			//从元数据中获取到所有的表名
			rs = db.getTables(null, null, null, new String[] { "TABLE" });
			while (rs.next()) {
				String tableName = rs.getString(3);
				if (driverClassName.contains("oracle")) {
					String user = rs.getString(2);
					if (user != null && user.equals(username.toUpperCase())) {
						tableNames.add(tableName);					
					}					
				} else {
					tableNames.add(tableName);
				}
			}
		} catch (SQLException e) {
			logger.error("getTableNames fail", e);
		} finally {
			try {
				rs.close();
				closeConnection(conn);
			} catch (SQLException e) {
				logger.error("close ResultSet fail", e);
			}
		}
		return tableNames;
	}
	
}
